//
//  MenuViewController.m
//  clublbiza
//
//  Created by WANG TOM on 9/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MenuViewController.h"
#import "TMDataTable.h"
#import "clublbizaAppDelegate.h"
#import "Resource.h"
#import "Ibizatv.h"
#import "PlayViewController.h"


#define ITEM_SIZE_WITH 180
#define ITEM_SIZE_HEIGHT 191

@interface MenuViewController ()

@end

@implementation MenuViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(refreshSubCatalogDataList)
                                                 name: @"currentSelectedMenuTabIndexChanged"
                                               object: nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
     return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}
- (void) refreshSubCatalogDataList
{
    AppMain *appMain = [AppMain shareInstance];
    int menuTabIndex = appMain.currentSelectedMenuTabIndex;
    if ( !(menuTabIndex > -1 &&  menuTabIndex < 3 )) {
        return;
    }
    //Remove all item views
    NSArray *subviews = [[self.view subviews] copy];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    [subviews release];
    
    
    
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    TMDataTable *dtObj = nil;
    switch (menuTabIndex) {
        case 0:
            dtObj = [[TMDataTable alloc] initWithTablename:@"Beverage" withPKName:@"uuid" contextProvider:appDelegate];
            break;
        case 1:
             dtObj = [[TMDataTable alloc] initWithTablename:@"Food" withPKName:@"uuid" contextProvider:appDelegate];
            break;
        case 2:
             dtObj = [[TMDataTable alloc] initWithTablename:@"Ibizatv" withPKName:@"uuid" contextProvider:appDelegate];
            break;
        default:
            break;
    }

      
    NSString *condition = @"active=1";
    NSArray *data_list = [dtObj findAll:condition withSort:@"order"];
    
    
    
    appMain.cacheMenuItemListData = data_list;
    
    
    TMDataTable *dtResource = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:appDelegate];
    int itemIndex = 0;
    
    int content_height = 0;
    for ( NSManagedObject *data_row in data_list )
    {
        //NSString *resource_uuid = suCatalogData.resource_uuid;
        /*
         Resource *resourceData = [dtResource find:resource_uuid];
         NSString *imgPath =  [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",resourceData.path];
         */
        
        UIView *itemView = [[self buildSubCatalogView:[data_row valueForKey:@"name_en"] withSubName:[data_row valueForKey:@"name_cn"] withItemIndex:itemIndex+1 itemVersionId:[[data_row valueForKey:@"version_id"] intValue]] retain];
        
        CGRect itemFrame = itemView.frame;
        itemFrame.origin = [self calculateItemViewLocation:itemIndex];
        itemView.frame = itemFrame;
        
        [self.view addSubview:itemView];
        
        
        
        content_height = itemView.frame.origin.y + itemView.frame.size.height;
        [itemView release];
        itemIndex++;
    }
    UIScrollView *scrollView = (UIScrollView*)self.view;
    CGSize contentSize = scrollView.contentSize;
    contentSize.height = content_height;
    scrollView.contentSize = contentSize;
    
    [dtObj release];
    [dtResource release];
}

- (UIView *) buildSubCatalogView:(NSString*)name withSubName:(NSString*)subName withItemIndex:(int)itemIndex itemVersionId:(int)versionid
{
    UIView *itemView = [[UIView alloc] init];
    [itemView setFrame:CGRectMake(0, 0, ITEM_SIZE_WITH, ITEM_SIZE_HEIGHT)];
    
    //UIImage *image = [[UIImage alloc] initWithContentsOfFile:imgPath];
    UIImage *image = [UIImage imageNamed:@"item_bg.png"];
    UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
    imgView.frame = itemView.frame;
    // imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.contentMode = UIViewContentModeScaleToFill;
    [itemView addSubview:imgView];
    [imgView release];
    
    //item index
    UILabel *indexLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 2, 25, 15)];
    indexLabel.text = [NSString stringWithFormat:@"%02d",itemIndex];
    [indexLabel setFont:[UIFont fontWithName:@"Verdana" size:12]];
    [indexLabel setBackgroundColor:[UIColor clearColor]];
    [indexLabel setTextColor:[UIColor colorWithRed:220/255.0 green:0.0 blue:0.0 alpha:1.0]];
    [itemView addSubview:indexLabel];
    [indexLabel release];
    
    //catalog name
    name = [name stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
    UILabel *nameLabel = [[UILabel alloc] init];
    [nameLabel setFont:[UIFont fontWithName:@"Arial" size:16]];
    nameLabel.lineBreakMode = UILineBreakModeWordWrap;  
    nameLabel.numberOfLines = 0; 
    [nameLabel setBackgroundColor:[UIColor clearColor]];
    CGSize sz = [name sizeWithFont:nameLabel.font constrainedToSize:CGSizeMake(160, 1000)];
    [nameLabel setFrame:CGRectMake(10, 30, 160, sz.height)];
    
    nameLabel.text = name;
    [nameLabel setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    [itemView addSubview:nameLabel];
    [nameLabel release];
    
    //catalog sub name
    UILabel *nameSubLabel = [[UILabel alloc] init];
    //[nameSubLabel setFont:[UIFont fontWithName:@"Arial" size:16]];
    nameSubLabel.lineBreakMode = UILineBreakModeWordWrap;  
    nameSubLabel.numberOfLines = 0; 
    [nameSubLabel setBackgroundColor:[UIColor clearColor]];
    sz = [subName sizeWithFont:nameSubLabel.font constrainedToSize:CGSizeMake(160, 1000)];
    [nameSubLabel setFrame:CGRectMake(10, nameLabel.frame.origin.y + nameLabel.frame.size.height + 5, 160, sz.height)];
    
    nameSubLabel.text = subName;
    [nameSubLabel setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    [itemView addSubview:nameSubLabel];
    [nameSubLabel release];
    
    //add transparent button
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = itemView.frame;
    btn.tag = versionid;
    [btn addTarget:self action:@selector(setCurrentSubCatalogAction:) forControlEvents:UIControlEventTouchUpInside];
    [itemView addSubview:btn];
    
    
    
    
    return [itemView autorelease];
}
- (void)setCurrentSubCatalogAction:(UIButton*)sender
{
    
    
    AppMain *appMain = [AppMain shareInstance];
    //Ibiza TV tab selected, play video
    if ( appMain.currentSelectedMenuTabIndex == 2 ) {
        clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
        
        TMDataTable *dtIbizatv = [[TMDataTable alloc] initWithTablename:@"Ibizatv" withPKName:@"uuid" contextProvider:appDelegate];
        Ibizatv *tvData = (Ibizatv*)[dtIbizatv findByField:@"version_id" withValue:[NSNumber numberWithInt:sender.tag] withSort:nil];
        
        if ( tvData.resource_uuid.length > 0 ) {
            TMDataTable *dtResource = [[TMDataTable alloc] initWithTablename:@"Resource" withPKName:@"uuid" contextProvider:appDelegate];
            Resource *resourceData = (Resource*)[dtResource find:tvData.resource_uuid];
            NSString *videoFilePath =  [[AppMain resourceFolderPath] stringByAppendingFormat:@"/%@",resourceData.path];
            [dtResource release];
            
            NSURL *videoURL = [NSURL fileURLWithPath:videoFilePath];
            
            
            
            
            
            PlayViewController *mpviewController = [[PlayViewController alloc] initWithNibName:@"PlayViewController" bundle:nil];
            mpviewController.videoListOpener = appDelegate.window.rootViewController;
            [mpviewController play:videoURL];
            [appDelegate.window.rootViewController presentModalViewController:mpviewController animated:NO];
            
            
        }
        [dtIbizatv release];
    }else{
        appMain.currentSelectedMenuVersionId = sender.tag;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"currentSelectedMenuVersionIdChanged" object:self];
    }
    
}
- (CGPoint) calculateItemViewLocation:(int)itemIndex
{
    float padding = 40;
    float h_space = 70;
    float v_space = 20;
    int h_item_number = 4;
    CGPoint loc = CGPointMake(0, 0);
    loc.y = padding + (ITEM_SIZE_HEIGHT+v_space)*floor(itemIndex/h_item_number);
    
    // int h_item_i = itemIndex < h_item_number?itemIndex+h_item_number:itemIndex;
    loc.x = padding + (ITEM_SIZE_WITH+h_space)*(itemIndex%h_item_number);
    return loc;
}
@end
